/**
 * 
 */
package com.zznode.client.wlanpolling.login;

import java.io.ByteArrayInputStream;

import javax.xml.xpath.XPathConstants;

import org.w3c.dom.Node;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.WLanContext;
import com.zznode.client.wlanpolling.main.MainTabActivity;
import com.zznode.client.wlanpolling.model.SystemSettingManager;
import com.zznode.client.wlanpolling.service.NetworkProber;
import com.zznode.client.wlanpolling.service.net.EnumHttpMethod;
import com.zznode.client.wlanpolling.service.net.HttpCallback;
import com.zznode.client.wlanpolling.service.net.HttpException;
import com.zznode.client.wlanpolling.service.net.HttpExecutorFactory;
import com.zznode.client.wlanpolling.service.net.HttpGetExecutor;
import com.zznode.client.wlanpolling.service.net.HttpParam;
import com.zznode.client.wlanpolling.service.xml.XmlParserException;
import com.zznode.client.wlanpolling.service.xml.XmlXPathAdaptor;
import com.zznode.client.wlanpolling.test.WLANPollingTabActivity;
import com.zznode.client.wlanpolling.utils.PingUtils;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;

/**
 * 
 *
 */
public class LoginActivity extends Activity implements HttpCallback {
	private static final String LOGIN_SUCCESS_STATUS = "1";
	private WLANPollingApplication application;
	
	private EditText edUsername;
	private EditText edPassword;
	private CheckBox ckRemeberPasword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.login);
		
		edUsername = (EditText)this.findViewById(R.id.username_login);
		edPassword = (EditText)this.findViewById(R.id.password_login);
		ckRemeberPasword = (CheckBox)findViewById(R.id.ckRemeberPasword);
		
		//TODO for test
		SharedPreferences preferences = getSharedPreferences(WLanPollingUtils.SYSTEM_SETTING, 0);
		WLanPollingUtils.serverAddress = preferences.getString(WLanPollingUtils.KEY_ADDRESS, WLanPollingUtils.DEFAULT_SERVEADDRESS);
		WLanPollingUtils.port = preferences.getString(WLanPollingUtils.KEY_PORT, WLanPollingUtils.DEFAULT_PORT);
		boolean savepassword = preferences.getBoolean(WLanPollingUtils.KET_SAVEPASSWORD, true);
		ckRemeberPasword.setChecked(savepassword);
		
		//load username
		preferences = getSharedPreferences(WLanPollingUtils.USER_INFO, 0);
		
		String username = null, password = null;
		if(ckRemeberPasword.isChecked()) {
			username = preferences.getString(WLanPollingUtils.USERNAME, "chuz");
			password = preferences.getString(WLanPollingUtils.PASSWORD, "chuz12345");
		} else{
			username = "";
			password = "";
		}
		
		edUsername.setText(username);
		edPassword.setText(password);
		
		application =  (WLANPollingApplication)getApplication();
		Button btn_login = (Button)this.findViewById(R.id.login_login);
		if(btn_login != null){
			btn_login.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					doLogin();
				}
			});
		}
		
		Button btn_exit = (Button)this.findViewById(R.id.exit_login);
		if(btn_exit != null){
			btn_exit.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					doExit();
				}
				
			});
		}
		
		ckRemeberPasword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				SharedPreferences preferences = getSharedPreferences(WLanPollingUtils.SYSTEM_SETTING, 0);
				SharedPreferences.Editor editor = preferences.edit();  
				editor.putBoolean(WLanPollingUtils.KET_SAVEPASSWORD, isChecked);  
				editor.commit();
			}
		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.login, menu);		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.exit) {
			doExit();
			return true;
		}
		
		if(item.getItemId() == R.id.netsetting) {
			Intent i = new Intent(LoginActivity.this, NetworkSettingActivity.class);
			startActivity(i);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	protected void doLogin(){
		NetworkProber prober = new NetworkProber(this);
		if(!prober.isWifi()) {
			android.app.AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this).setTitle("提示").setMessage("无法登录系统必须使用Wifi网络进行巡检测试, 请设置Wifi信息");
			builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");  
					startActivity(wifiSettingsIntent); 
				}
			});
			
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			
			builder.show();
			return;
		}
		
		//connect to network and verify username & password.
		HttpGetExecutor executor = (HttpGetExecutor)HttpExecutorFactory.createHttpExecutor(EnumHttpMethod.GET);
		executor.setUrl(WLanPollingUtils.getLoginURL());
		
		String username = edUsername.getText().toString();
		String password = edPassword.getText().toString();
		
		if((username == null || username.length() == 0) || (password == null || password.length() == 0)) {
			Toast.makeText(getApplicationContext(), "用户名/密码为空", Toast.LENGTH_LONG).show();
			return;
		}
		
		if(ckRemeberPasword.isChecked()) {
			SharedPreferences settings = getSharedPreferences(WLanPollingUtils.USER_INFO, 0);  
			SharedPreferences.Editor editor = settings.edit();  
			editor.putString(WLanPollingUtils.USERNAME, username);  
			editor.putString(WLanPollingUtils.PASSWORD, password);
			editor.commit();
		}
		
		executor.addParam(new HttpParam("username", username));
		executor.addParam(new HttpParam("password", password));
		
		//TODO
		LinearLayout layout = (LinearLayout)findViewById(R.id.loginProgressbarLayout);
		layout.setVisibility(View.VISIBLE);
		showOrHideProgressBar(true, "正在登录系统...");
		executor.asyncExecute(this, 0);
	}
	
	private void showOrHideProgressBar(final boolean flag, final String msg) {
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				LinearLayout layout = (LinearLayout)findViewById(R.id.loginProgressbarLayout);
				if(flag) {
					layout.setVisibility(View.VISIBLE);
					TextView tip = (TextView)findViewById(R.id.loginMsgTip);
					tip.setText(msg);
				} else {
					layout.setVisibility(View.GONE);
				}
			}
		});
	}
	
	protected void doExit(){
		finish();
		System.exit(0);
	}

	@Override
	public void onReceiveData(byte[] data, final HttpException exp, int tag) {
		stopLogin();
		
		if(exp != null) {
			//提示登录失败，出现错误
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), exp.getMessage(), Toast.LENGTH_LONG).show();
				}
			}) ;
			
			//TODO for test
			//startActivity(new Intent(this, WLANPollingTabActivity.class));
			//finish();
			return;
		}
		
		try {
			XmlXPathAdaptor xpathAdaptor = new XmlXPathAdaptor(new ByteArrayInputStream(data));
			
			Node ifuser = (Node)xpathAdaptor.evaluate("/NODE/IFUSER", XPathConstants.NODE);
			Node areaid = (Node)xpathAdaptor.evaluate("/NODE/AREAID", XPathConstants.NODE);
			Node cityCode = (Node)xpathAdaptor.evaluate("/NODE/CITYCODE", XPathConstants.NODE);
			Node uid = (Node)xpathAdaptor.evaluate("/NODE/UID", XPathConstants.NODE);
			 
			if(ifuser != null && LOGIN_SUCCESS_STATUS.equalsIgnoreCase(ifuser.getTextContent().trim())) {
				WLanContext context = application.getContext();
				
				context.setAreaId(areaid.getTextContent().trim());
				context.setCityCode(cityCode.getTextContent().trim());
				context.setUid(uid.getTextContent().trim());
				
				SystemSettingManager systemSettingManager = new SystemSettingManager(getApplicationContext());
				context.setSystemSetting(systemSettingManager.getSystemSetting());
				
				//进入主界面
				startActivity(new Intent(this, PingUtils.isEmulator(this) ? WLANPollingTabActivity.class : MainTabActivity.class)); // only for test
				
				finish();
				
				return;
			} else {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), "登录失败,用户没有注册或者密码错误", Toast.LENGTH_LONG).show();
					}
				}) ;
			}

		} catch (final XmlParserException e) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}) ;
		}

		return;
	}	
	
	private void stopLogin() {
		showOrHideProgressBar(false, null);
	}
}
